package com.definesys.smecrailtransit.module.lineCharts.Fragment;

import android.app.ProgressDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentChartsMonBinding;
import com.definesys.smecrailtransit.module.lineCharts.LineChartsActivity;
import com.definesys.smecrailtransit.module.lineCharts.LineChartsPresenter;
import com.definesys.smecrailtransit.module.lineCharts.adapter.SmecErrorEleAdapter;
import com.definesys.smecrailtransit.module.lineCharts.beans.MonReport;
import com.definesys.smecrailtransit.module.lineCharts.viewModel.MonthReportViewModel;
import com.definesys.smecrailtransit.widget.ChartsController;
import com.github.mikephil.charting.charts.PieChart;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.WeakHashMap;

import static android.view.View.VISIBLE;
import static com.definesys.smecrailtransit.module.lineCharts.viewModel.MonthReportViewModel.selectedMonth;
import static com.prolificinteractive.materialcalendarview.CalendarMode.MONTHS;

/**
 * Created by xupeizuo on 2018/3/5.
 */

public class MonthFragment extends SmecBaseFragment<LineChartsPresenter> {

    private FragmentChartsMonBinding fragmentChartsMonBinding;
    public static final String GET_MON_REPORT_SUCCESS="GET_MON_REPORT_SUCCESS";
    public static final String GET_MON_REPORT_FAIL="GET_MON_REPORT_FAIL";
    private Calendar calendar = Calendar.getInstance();
    private static final SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM");
    private MonthReportViewModel monthReportViewModel;
    private ProgressDialog progressDialog;
    private ChartsController barCharts;
    private SmecErrorEleAdapter smecErrorEleAdapter;

    @Override
    protected LineChartsPresenter getPersenter() {
        return new LineChartsPresenter(getContext());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentChartsMonBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_charts_mon,container,false);
        initView();
        fragmentChartsMonBinding.setMonView(monthReportViewModel);
        return fragmentChartsMonBinding.getRoot();
    }

    public void initView(){
        monthReportViewModel=new MonthReportViewModel(mRxBus,getContext());
        initBarChart();
        setDate();
        calendarlistener();
        smecErrorEleAdapter=new SmecErrorEleAdapter(getContext());
        fragmentChartsMonBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        fragmentChartsMonBinding.recyclerView.setAdapter(smecErrorEleAdapter);
    }

    /**
     * 如果当前在7点之前则请求昨天的数据
     */
    private void setDate(){
        String requestDate="";
        int now=calendar.get(Calendar.DATE);
        if(now<10){
            fragmentChartsMonBinding.calendarText.setText(calendar.get(Calendar.YEAR)+"年"+calendar.get(Calendar.MONTH)+"月");
            calendar.add(Calendar.MONTH, -1);
            requestDate=sim.format(calendar.getTime());
        }else {
            fragmentChartsMonBinding.calendarText.setText(calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月");
            requestDate=sim.format(new Date());
        }
        mPresenter.getMonReport(requestDate);
    }


    /**
     * 日期选择器
     */
    public void calendarlistener(){
        fragmentChartsMonBinding.chooseDate.setOnClickListener(v -> monthReportViewModel.showMonthData());
    }

    private void dealWithData(MonReport monReport){
        dealChart(fragmentChartsMonBinding.pieChartY,monReport.getCallFaultCount(),monReport.getAutoFaultCount(),new String[]{"#ba4689","#82d7e9"});
        dealChart(fragmentChartsMonBinding.pieChartY2,monReport.getFtFaultCount(),monReport.getNotSelfFaultCount(),new String[]{"#ad58e7","#d97c5f"});

    }

    private void dealChart(PieChart mPieChart, int num1, int num2, String[] coArr){
        ChartsController chartsController =new ChartsController(mPieChart,getContext(),coArr);
        chartsController.initPie();
        ArrayList<Integer> list2=new ArrayList<>();
        list2.add(num1);
        list2.add(num2);
        chartsController.setPieData(list2);
        chartsController.startLoaf();
    }

    /**
     * 初始化柱状图
     */
    private void initBarChart(){
        barCharts=new ChartsController(fragmentChartsMonBinding.barChart1,getContext());
    }

    public void initBarChartData(MonReport monReport){
        try {
            barCharts.initBar(fragmentChartsMonBinding.barChart1,monReport.getFaultStationList());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取月报信息
     * @param month
     */
    public void getMonthReportMesg(String month){

        if(progressDialog == null){
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在获取月度报表信息请稍后...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        fragmentChartsMonBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                progressDialog.show();
                mPresenter.getMonReport(month);
            }
        },400);

    }

    public static MonthFragment newInstance() {
        Bundle args = new Bundle();
        MonthFragment fragment = new MonthFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_MON_REPORT_FAIL)
            }
    )
    public void getDayReportFail(Object o){
        fragmentChartsMonBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(progressDialog!=null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }
        },700);
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_MON_REPORT_SUCCESS)
            }
    )
    public void getDayReportSuccess(MonReport monReport){
        fragmentChartsMonBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(progressDialog!=null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }
        },700);
        monthReportViewModel.setMonReport(monReport);
        dealWithData(monReport);
        initBarChartData(monReport);
        smecErrorEleAdapter.setArrayList(monReport.getFaultEleList());
        fragmentChartsMonBinding.invalidateAll();
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(selectedMonth)
            }
    )
    public void getSelectedDate(WeakHashMap<String,String> map){
        String date=map.get("selected");
        String dateZW=map.get("selectedZW");
        fragmentChartsMonBinding.calendarText.setText(dateZW);
        getMonthReportMesg(date);
    }
}
